"""
认证相关依赖注入

提供获取当前用户等依赖
"""

from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from sqlalchemy.orm import Session
import sys
from pathlib import Path

# 处理导入路径
if __name__ == "__main__" or "." not in __name__:
    sys.path.insert(0, str(Path(__file__).parent.parent.parent))
    from stage2_advanced.chapter02_jwt.security import decode_token
    from stage2_advanced.chapter02_jwt.database import get_db
    from stage2_advanced.chapter02_jwt import crud, models
else:
    from .security import decode_token
    from .database import get_db
    from . import crud, models


# ========== OAuth2 配置 ==========

# OAuth2 密码流程的 Token URL
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth/login")
# tokenUrl 是登录接口的路径（相对于 app 根路径）


# ========== 获取当前用户 ==========

def get_current_user(
    token: str = Depends(oauth2_scheme),
    db: Session = Depends(get_db),
) -> models.User:
    """
    获取当前登录用户
    
    从 Token 中提取用户信息，并从数据库查询完整用户数据
    
    Args:
        token: JWT Token（由 OAuth2PasswordBearer 自动提取）
        db: 数据库会话
        
    Returns:
        当前用户对象
        
    Raises:
        HTTPException: Token 无效或用户不存在
    """
    # 定义认证失败异常
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    
    # 1. 从 Token 提取用户名
    username = decode_token(token)
    if username is None:
        raise credentials_exception
    
    # 2. 从数据库查询用户
    user = crud.get_user_by_username(db, username=username)
    if user is None:
        raise credentials_exception
    
    # 3. 检查用户状态
    if not user.is_active:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Inactive user",
        )
    
    return user


def get_current_active_user(
    current_user: models.User = Depends(get_current_user),
) -> models.User:
    """
    获取当前活跃用户
    
    额外检查用户是否活跃
    
    Args:
        current_user: 当前用户（由 get_current_user 依赖提供）
        
    Returns:
        当前活跃用户对象
        
    Raises:
        HTTPException: 用户未激活
    """
    if not current_user.is_active:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Inactive user"
        )
    return current_user


def require_admin(
    current_user: models.User = Depends(get_current_user),
) -> models.User:
    """
    要求管理员权限
    
    Args:
        current_user: 当前用户（由 get_current_user 依赖提供）
        
    Returns:
        当前管理员用户对象
        
    Raises:
        HTTPException: 用户没有管理员权限
    """
    if not current_user.is_superuser:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Not enough permissions. Admin access required."
        )
    return current_user


